﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Browser;

namespace SilverQuery
{
	/// <summary>
	/// Managed wrapper around the jQuery Event object.
	/// </summary>
	public class Event
	{
		private ScriptObject _nativeEvent;
		private Nullable<int> _pageX;
		private Nullable<int> _pageY;
		private HtmlObject _target;
		private HtmlObject _currentTarget;
		private HtmlObject _relatedTarget;
		private string _type;
		private Nullable<int> _keyCode;

		internal static Event Create(ScriptObject eventObject)
		{
			var evt = new Event();
			evt._nativeEvent = eventObject;
			return evt;
		}

		public void stopPropagation()
		{
			_nativeEvent.Invoke("stopPropagation");
		}

		public void preventDefault()
		{
			_nativeEvent.Invoke("preventDefault");
		}

		/// <summary>
		/// The DOM element that issued the event.
		/// </summary>
		public HtmlObject target
		{
			get
			{
				if (_target == null)
					_target = (HtmlObject)_nativeEvent.GetProperty("target");
				return _target;
			}
		}

		/// <summary>
		/// The current DOM element within the event bubbling phase.
		/// </summary>
		/// <remarks>
		/// This is the same element as what the "this" context refers to in jQuery.
		/// </remarks>
		public HtmlObject currentTarget
		{
			get
			{
				if (_currentTarget == null)
					_currentTarget = (HtmlObject)_nativeEvent.GetProperty("currentTarget");
				return _currentTarget;
			}	
		}

		/// <summary>
		/// On mouse movement, contains the DOM element which the mouse was previously on when moving onto or off of an element.
		/// </summary>
		public HtmlObject relatedTarget
		{
			get
			{
				if (_relatedTarget == null)
					_relatedTarget = (HtmlObject)_nativeEvent.GetProperty("relatedTarget");
				return _relatedTarget;
			}
		}

		/// <summary>
		/// The X mouse coordinate relative to the document.
		/// </summary>
		public int pageX
		{
			get
			{
				if (!_pageX.HasValue)
					_pageX = Convert.ToInt32(_nativeEvent.GetProperty("pageX"));
				return _pageX.Value;
			}
		}

		/// <summary>
		/// The Y mouse coordinate relative to the document.
		/// </summary>
		public int pageY
		{
			get
			{
				if (!_pageY.HasValue)
					_pageY = Convert.ToInt32(_nativeEvent.GetProperty("pageY"));
				return _pageY.Value;
			}
		}

		/// <summary>
		/// The ASCII code for the key that was pressed.
		/// </summary>
		public int keyCode
		{
			get
			{
				if (!_keyCode.HasValue)
					_keyCode = Convert.ToInt32(_nativeEvent.GetProperty("keyCode"));

				return _keyCode.Value;
			}
		}

		/// <summary>
		/// The name of the event.
		/// </summary>
		public string type
		{
			get
			{
				if (_type == null)
					_type = (string)_nativeEvent.GetProperty("type");
				return _type;
			}
		}
	}
}